<template>
	<form @submit.stop.prevent="formSubmit">
		<view style="padding:40rpx;">
			<!-- <view class="label"> 请选择动态密码的开始和结束时间 </view> -->
			<uni-datetime-picker v-model="datetimerange" type="datetimerange" rangeSeparator="至">
				<view class="form-item picker">
					<text>{{startTime?startTime +'~'+endTime:'请选择动态密码的开始和结束时间'}}</text>
					<uni-icons type="forward" color="#777777"></uni-icons>
				</view>
			</uni-datetime-picker>
			<view class="form-item">
				<input class="input" type="number" placeholder="请输入有效次数" placeholder-style="font-size:26rpx" name="vaildNum" v-model="vaildNum" />
			</view>
			<view class="form-item">
				<input class="input" password type="password" placeholder="请输入动态密码" placeholder-style="font-size:26rpx" name="password" v-model="password" />
			</view>
			<!-- <view class="form-item" style="border:none">
				<view style="font-size: 24rpx;color: #999999;">密码长度8-64位，由数字、字母和符号组成</view>
			</view> -->
			<view class="form-item form-item-submit">
				<button class="block" type="primary" form-type="submit" style="margin-bottom: 10rpx">确认设置密码</button>
			</view>
		</view>
		<!-- 登录 -->
		<j-device-login ref="deviceLogin" :device="device" @submit="submit"></j-device-login>
	</form>
</template>

<script>
const CryptoJS = require('crypto-js');

export default {
    data() {
        return {
            token: '',
            deviceNo: '',
            devUserName: '',
            password: '',
            newPassword: '',
            confirmPassword: '',
			datetimerange:[],
			startTime:'',
			endTime:'',
			vaildNum:'',
			// 设备对象
			device: {
			},
			// 缓存列表
			deviceList: [],
			
			// 是否存在缓存
			isCache: false,
			
			//保活定时器
			timer: null,
			
			// 保活次数迭代变量
			keepAliveCount: 0,
        };
    },
	watch: {
		datetimerange(newval) {
			console.log('范围选:', this.datetimerange);
			this.startTime = this.datetimerange[0]
			this.endTime = this.datetimerange[1]
		}		
	},
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
		this.device = JSON.parse(options.device)
        console.log('=== device-live:setting:password:', this.device,options);
		this.token = this.device.token
		this.deviceNo = this.device.deviceNo
		this.devUserName = this.device.devUserName
		this.getCurrentDevice(options)
		this.getInit()
    }, 
	onUnload() {
		clearInterval(this.timer);
		this.timer = null
	},
    methods: {
        //设置动态密码
        formSubmit(ev) {
            if (this.startTime == '' || this.endTime == '') {
                uni.showToast({
                    title: '请选择开始和结束时间'
                });
                return;
            }
            if (this.password.replace(/\s/g, '') === '') {
                uni.showToast({
                    title: '请输入动态密码'
                });
                return;
            }
            uni.showLoading({
            	title:'正在设置'
            });
            const token =  this.device.token;
            const data = {
				sn: this.deviceNo,
				props:{
					doorLock:{
						tempPassword:[
							{
								endTime: this.endTime,
								password: this.password,
								startTime: this.startTime, 
								vaildNum: this.vaildNum
							}
						]
					}
				},	
            };
            getApp().globalData.api.setTemporaryPassword(data, token, (result) => {
                uni.hideLoading();
				console.log(result);
                if (result.Ret === 100) {
                	uni.showToast({
                	    title: '密码设置成功',
						success: () => {
							uni.navigateBack({ })
						}
                	});
					
                }else {
                    uni.showToast({
                        title: result.data.msg
                    });
                }
            });
        },
		
		// 循环对比获取当前设备，否则使用传参设备
		getCurrentDevice(options) {
			let device = JSON.parse(options.device);
			let deviceList = uni.getStorageSync('deviceList') || [];
			let bool = false;
		
			for (let i = 0; i < deviceList.length; i++) {
				const item = deviceList[i];
				if (item.deviceNo === device.deviceNo) {
					bool = true;
					this.device = item
					this.deviceList = deviceList
					this.isCache = true
					break;
				}
			}
		
			if (!bool) {
				this.device = device
				this.deviceList.push(device)
				this.isCache = false
			}
		},

		getInit(){
			let sns = []
			sns.push(this.device.deviceNo)
			this.getDeviceToken(sns)
		},
		
		// 获取设备token
		getDeviceToken(sns) {
		    const data = {
		        sns: sns
		    };
			console.log('app:',getApp());
		    getApp().globalData.api.getDeviceToken(data, (result) => {
		        console.log('获取设备token:', result);
				// 遍历缓存更新当前设备的token
		        this.deviceList.forEach((item) => {
		            result.forEach((pro) => {
		                if (item.deviceNo === pro.sn) {
		                    item.token = pro.token;
							this.device = item
		                }
		            });
		        });
				// 根据token查询当前设置状态
		        let tokenList = [];
		        result.forEach((item) => {
		            tokenList.push(item.token);
		        });
		        this.getDeviceStatus(tokenList, this.deviceList);
		    });
		},
		// 获取设备状态
		getDeviceStatus(tokenList, deviceList) {
		    const data = {
		        token: tokenList
		    };
		    getApp().globalData.api.getDeviceStatus(data, (result) => {
				// 遍历缓存增加或更新当前设备的status
		        deviceList.forEach((item) => {
		            result.forEach((pro) => {
		                if (item.deviceNo === pro.uuid) {
							this.$set(item,'status',pro)
							this.device = item
		                }
		            });
		        });
				// 遍历缓存更新BOSS中当前设备的token和status
				let bossDeviceList = uni.getStorageSync('bossDeviceList')
				bossDeviceList.forEach(item => {
					deviceList.forEach(pro => {
						if (item.deviceNo === pro.deviceNo) {
							item.token = pro.token
							item.status = pro.status
						}
					})
				})
				// 存储缓存
				uni.setStorageSync('deviceList',deviceList)
				uni.setStorageSync('bossDeviceList',bossDeviceList)
				this.getMore()
		    });
		},
		// 第1步 根据传参过来的设备对象以及对象状态，做一系列的判断和准备操作
		getMore() {
			let status = this.device.status; // 在线
		
			if (status.status === 'online') {
				// 低功耗设备-已休眠
				if (status.wakeUpStatus === 0) {
					// 支持远程唤醒
					if (status.wakeUpEnable === '1') {
						uni.showLoading({
							title: '唤醒设备中...'
						}); //唤醒设备
		
						this.wakeup(() => {
							uni.hideLoading({
								success: (res) => {
									this.loginOrAuto();
								}
							});
						});
					} 
					// 不支持远程唤醒（手动唤醒）
					else {
						uni.showModal({
							title: '提示',
							content: '该设备深度休眠中，需要手动唤醒！',
							showCancel: false,
							success: (res) => {
								uni.navigateBack({
									delta: 1
								});
							}
						});
					}
				} // 低功耗设备-已唤醒
				else if (status.wakeUpStatus === 1) {
					this.loginOrAuto();
				} // 普通设备
				else {
					this.loginOrAuto();
				}
			}
		},
		
		// 低功耗设备唤醒
		wakeup(callback) {
			let data={
				sn:this.device.deviceNo,
				hostedControl:"1",//是否唤醒主控（空值或0：不唤醒主控；1：唤醒主控）
			}
			getApp().globalData.api.wakeup(data,this.device.token, (result) => {
				callback();
			});
		},
		
		// 第2步 手动登录或自动登录
		loginOrAuto() {
			if (!this.isCache) {
				this.$refs.deviceLogin.open()
			} else {
				this.$refs.deviceLogin.submit(this.device.devUserName, this.device.devPassWord)
			}
		},
		
		// 第3步 登录
		submit(options) {
			// 缓存登录信息
			if (!this.isCache) {
				this.saveLoginInfo(options);
			}
			// 保活
			this.initKeepAlive();
		},
		
		// 缓存登录信息
		saveLoginInfo(options) {
			let deviceList = uni.getStorageSync('deviceList') || [];
			this.device.devUserName = options.username;
			this.device.devPassWord = options.password;
			deviceList.push(this.device);
			uni.setStorageSync('deviceList', deviceList);
		},
		
		// 第4步-1 保活
		// 20秒执行一次，当连续请求两次保活失败时，则不再保活
		initKeepAlive() {
			console.log('定时器：', this.timer);
		
			if (this.timer !== null) {
				clearInterval(this.timer);
				this.timer = null
			}
		
			this.timer = setInterval(() => {
				this.keepAlive();
			}, 20000)
		},
		
		// 保活
		keepAlive() {
			let token = this.device.token;
			getApp().globalData.api.keepAlive(token, (result) => {
				// console.log('保活：', result);
		
				if (result.data.code === 2000) {
					if (result.data.data.Ret === 100) {
						// 不需要操作
					} else {
						if (this.keepAliveCount === 0) {
							this.keepAliveCount = this.keepAliveCount + 1
							this.initKeepAlive();
						} else {
							clearInterval(this.timer);
						}
					}
				} else {
					if (this.keepAliveCount === 0) {
						this.keepAliveCount = this.keepAliveCount + 1
						this.initKeepAlive();
					} else {
						clearInterval(this.timer);
					}
				}
			});
		},
		// 一直请求直到请求成功（处理：渲染层网络层错误）
		keepRequestUntillRight(url) {
			console.log('=====一直请求直到请求成功=======');
			uni.request({
				method: 'GET',
				url,
				success: (res) => {
					if (res.statusCode == 200) {
						this.url = url
						this.isLoading = false
					} else if (res.statusCode == 400) {
						uni.showModal({
							title: '提示',
							content: res.data,
							showCancel: false
						});
					} else {
						setTimeout(() => {
							this.keepRequestUntillRight(url);
						}, 1000);
					}
				},
				fail: (err) => {
					console.log('error:', err);
				}
			});
		},
		
    }
};
</script>
<style>
page {
    background-color: #ffffff;
}
.label{
	font-size: 28rpx;
	color: #999999;
	margin-bottom: 20rpx;
}
.form {
    padding: 0 80rpx;
}
.picker{
	color: #777777;
	font-size: 26rpx;
	display: flex;
	justify-content: space-between;
}

.form-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    border-bottom: 1px solid #eeeeee;
    padding: 30rpx 0; 
}
.input{
	font-size: 26rpx;
}

.form-item-title {
    width: 200rpx;
}
.form-item-control {
    justify-content: space-between;
    color: #777777;
    margin-bottom: 80rpx;
    border-bottom: none;
}
.form-item-submit {
    flex-direction: column;
    border-bottom: none;
	margin-top: 60rpx;
}
</style>
